package circuitbreaker

import (
	"context"
	"github.com/go-kratos/aegis/circuitbreaker"
	"google.golang.org/grpc"
)

type InterceptorBuilder struct {
	breaker circuitbreaker.CircuitBreaker
}

func (b *InterceptorBuilder) BuilderServerInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		err := b.breaker.Allow()
		if err == nil {
			resp, err := handler(ctx, req)
			if err != nil {
				//这里没有区别业务错误和系统错误
				//需要进一步区别错误
				//s, ok := status.FromError(err)
				//if s.Code() == codes.Unavailable {}
				b.breaker.MarkFailed()
			} else {
				b.breaker.MarkSuccess()
			}
			return resp, err
		}
		b.breaker.MarkFailed()
		return nil, err

	}
}
